import json
from datetime import datetime
from random import random
from urllib import parse
from urllib.parse import urlparse

from django.http import JsonResponse

from lapi_app.models.environment_model.environment import Environment
from lapi_app.models.testcase_model.testcase import Testcase
from lapi_app.models.testcase_model.testcase_tree import Menu
from lapi_app.view.testcase_view.curl_input import curl_to_request_kwargs


def curl_input_case(request):
    try:
        data = json.loads(request.body)
        if data["curl_data"] == "":
            return JsonResponse({
                "code": 100,
                "message": "必要参数不可为空"
            })
        else:
            curl_data = data["curl_data"]
            pid = data["menu_id"]
            user_id = data["user_id"]
            result = {}
            curl_result = curl_to_request_kwargs(curl_data)
            url = urlparse(curl_result["url"])
            host = url.scheme + "://" + url.netloc
            params_list = []
            for key, value in dict(parse.parse_qsl(url.query)).items():
                params_dict = {"key": key, "value": value}
                params_list.append(params_dict)
            if Environment.objects.filter(e_address=host):

                env = Environment.objects.get(e_address=host)
                result.update({"environment_id": env.id})
            else:
                result.update({"environment_id": 1})
            if "body" in curl_result.keys():
                result.update({"body": curl_result["body"], "body_type": curl_result["body_type"]})
            else:
                result.update({"body": {}, "body_type": 2})
            result.update({"path": url.path, "params": params_list,
                           "assert_form": [], "extract": [], "api_type": 1,
                           "name": "CURL导入" + datetime.now().strftime("%H:%M"),
                           "headers": curl_result["headers"], "menu_id": pid, "method": 2})
            # 不忽略未知参数
            # result = curl_to_request_kwargs(curl_command,False)
            c = Testcase.objects.create(t_name=result["name"], t_method=result["method"],
                                        t_url=result["path"], t_params=result["params"], t_type=result["body_type"],
                                        t_header=result["headers"], t_body=result["body"],
                                        update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                        create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                        t_user_id=user_id, t_environment_id=result["environment_id"])
            menu = Menu.objects.create(label=result["name"], pid=pid, type=2, m_user_id=user_id, testcase_id=c.id)
            return JsonResponse({
                "code": 200,
                "message": "导入接口成功",
                "data": {"id": menu.id, "type": menu.type, "label": menu.label, "pid": pid}
            })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })
